package com.lc.controller;

import com.lc.constant.Constants;
import com.lc.result.Result;
import com.lc.result.ResultEnum;
import com.lc.result.ResultUtils;
import com.lc.service.thirdparty.wangyiyun.SMService;
import com.lc.utils.SmsUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 发送短信验证码
 * @Author lc
 */
@RestController
@RequestMapping("/ums")
public class UmsController {

    @Resource
    private SMService smService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("sms/sendSms")
    public Result sendSms(String phone, Integer codeType){

        //非空验证
        if (!SmsUtil.isEmpty(phone)) {
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_PHONE_ERROR);
        }
        //格式验证
        if (!SmsUtil.matchReg(phone)) {
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_PHONE_ERROR);
        }
        //短信类型校验
        if (!SmsUtil.codeType(codeType)) {
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_SMS_CODE_TYPE_ERROR);
        }

        //校验60秒内不会重复为同一个手机号发送相同类型的短信验证码
        //获取原来Redis中短信验证码的key
        String redisKey = Constants.Redis.PREFIX_SMS + phone;
        //判断key是否存在
        Boolean exist = redisTemplate.hasKey(redisKey);
        if (exist) {
            //key存在，说明60秒内已发送过验证码，返回错误信息
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_SMS_SEND_REPEAT);
        }

//        //发送短信
//        String sendCode = smService.sendCode(phone);
//        //使用JsonUtil解析JSON数据
//        JSONObject data = JSONUtil.parseObj(sendCode);
//        //提取特定信息
//        String sendSms = data.getStr("obj");

        //模拟短信验证码
        String sendSms = "1234";

        //存入redis中
        redisTemplate.opsForValue().set(Constants.Redis.PREFIX_SMS+phone,sendSms,5, TimeUnit.MINUTES);
        // 设置60秒内不能发送相同类型的验证码
        redisTemplate.opsForValue().setIfAbsent(redisKey, "sendSms", 60, TimeUnit.SECONDS);

        return ResultUtils.returnSuccess();
    }

}
